# -*- coding: utf-8 -*-
# created on 2017/05/04

from sympy import Symbol
from mathsolver.functions.base import BaseFunction, BaseFunc, BaseValue, BasePieceFunc
from mathsolver.functions.hanshu.fenduanhanshu_qiucan import FenDuanHanShuFangCheng
from mathsolver.functions.hanshu.zuizhi_new import MaxValue


def zuizhi_output_transform(zuizhi_output0):
    """最大、最小值输出结果转换
    
    最值输出： 
        如果含参数 {canshu_range: [min_max_val, (x_val, reacheable)], ... }
        如果不含参数 [min_max_val, (x_val, reacheable)]
    
    转换结果：
        如果含参数：BasePiecefunc()
        如果不含参数 BaseFunc """
    assert isinstance(zuizhi_output0, BaseValue)
    output_value = zuizhi_output0.value

    if isinstance(output_value, dict):
        piecefunc_expr = []
        symbols = set()
        for canshu_range, (min_max_val, (_, _)) in output_value.items():
            piecefunc_expr.append([min_max_val, canshu_range])
            try:
                symbols = symbols.union(min_max_val.free_symbols)
            except Exception:
                # free_symbols 可能报错
                continue
        var = symbols.pop()
        return BasePieceFunc({"var": var, "name": "f", "type": "", "expression": piecefunc_expr})
    else:
        min_max_val, (_, _) = output_value
        try:
            var = min_max_val.free_symbols.pop()
        except Exception:
            var = Symbol('x')

        return BaseFunc({"var": var, "name": "f", "type": "", "expression": min_max_val})


class ZuiDaZhiFenDuanHanShuQiuCan(BaseFunction):
    def solver(self, *args):
        func, interval, number = args
        number = number.sympify()

        # 计算最值
        max_solver = MaxValue(self.known).solver(func, interval)

        # 最值结果转换
        func = zuizhi_output_transform(max_solver.output[0])

        # 解（分段）函数最值等式
        fangcheng = BaseFunc({"var": func.var, "name": "f", "type": "", "expression": number})
        fenduan_solver = FenDuanHanShuFangCheng().solver(func, fangcheng)

        self.output = fenduan_solver.output
        return self


if __name__ == '__main__':
    pass
